<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Image_uploader extends CI_Controller
{
	private $sizeLimit = 5120000;
	private $user_id;
	
	function __construct()
	{
		parent::__construct();
		
		$this->load->config('layout', TRUE);
		$this->load->helper('url');
		$this->load->library('security');
		$this->load->library('session');
		$this->user_id = $this->session->userdata('user_id');
	}
	
	function uploadToTemp()
	{
		$user_id = $this->user_id;
		$tempDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_temp', 'layout').$user_id.'/';
		$imageTempURL = $this->config->item('image_uploader_temp', 'layout').$user_id.'/';
		$allowedExtensions = array("jpeg", "jpg", "gif", "png");
		$allowedExtensions = array_map("strtolower", $allowedExtensions);
		
		$this->checkServerSettings();
		
		if (!is_writable($tempDirectory)){
			mkdir($tempDirectory);
        }
		
		$size = $this->getSize();
		
        if ($size == 0) {
			echo htmlspecialchars(json_encode(array('error' => 'File is empty')), ENT_NOQUOTES);
			exit;
        }
        
        if ($size > $this->sizeLimit) {
            echo htmlspecialchars(json_encode(array('error' => 'File is too large')), ENT_NOQUOTES);
			exit;
        }
        
        $pathinfo = pathinfo($this->getName());
        $filename = time();
        //$filename = $pathinfo['filename'];
        //$filename = md5(uniqid());
        $ext = @$pathinfo['extension'];		// hide notices if extension is empty

        if($allowedExtensions && !in_array(strtolower($ext), $allowedExtensions)){
            $these = implode(', ', $allowedExtensions);
			echo htmlspecialchars(json_encode(array('error' => 'File has an invalid extension, it should be one of '. $these . '.')), ENT_NOQUOTES);
			exit;
        }
        
        $ext = ($ext == '') ? $ext : '.' . $ext;
		/*
        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . $ext)) {
                $filename .= rand(10, 99);
            }
        }
        */
        
        if ($this->save($tempDirectory . $filename . $ext, $tempDirectory.'thumbs_'.$filename . $ext)){
            $result =  array('success'=>true,'thumbs'=>'<img src="'.$imageTempURL. 'thumbs_'.$filename . $ext.'" />','filename'=>$filename . $ext);
        } else {
            $result =  array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
		
		echo json_encode($result);
	}
	
	

	function cancelUpload(){ // just delete images in temp dir
		sleep(1);
		$user_id = $this->user_id;
		$tempDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_temp', 'layout').$user_id.'/';
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		
		if(is_readable($tempDirectory.$data['filename'])){
			unlink($tempDirectory.$data['filename']);
		}
		
		if(is_readable($tempDirectory.'thumbs_'.$data['filename'])){
			unlink($tempDirectory.'thumbs_'.$data['filename']);
		}
		
		return true; //delete successfully
	}
	
	function delete_temp_files(){
		$data = $this->input->post(NULL, TRUE);
		$tempDirectory = $_SERVER["DOCUMENT_ROOT"].$this->config->item('image_uploader_temp', 'layout').$this->user_id.'/';
		$upload_images = json_decode($data['upload_image']);
		
		foreach($upload_images as $images){
			if(is_readable($tempDirectory.$images)){
				unlink($tempDirectory.$images);
				unlink($tempDirectory.'thumbs_'.$images);
			}	
		}
		
		return;
	}
	
	private function resizeImage($originalFileName,$fileName){
		$t_width = 117; // Maximum thumbnail width
		$t_height = 80; // Maximum thumbnail height
		$construct = array('fileName'=>$originalFileName);
		$this->load->library('Resize',$construct);
		$this->resize->resizeImage($t_width, $t_height, 0);
   		$this->resize->saveImage($fileName, 100);
	}
	
	private function checkServerSettings(){        
        $postSize = $this->toBytes(ini_get('post_max_size'));
        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
        
        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
            die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
        }        
    }
	
	private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }
	
	function save($path,$thumbspath) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        
        if ($realSize != $this->getSize()){            
            return false;
        }
        
        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
		
        stream_copy_to_stream($temp, $target);
        fclose($target);
        
		$this->resizeImage($path,$thumbspath);
		
		
        return true;
    }
	
	function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"];            
        } else {
            throw new Exception('Getting content length is not supported.');
        }      
    }
	
	function getName() {
        return $_GET['qqfile'];
    }
}